package com.example.uberorganizer;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

import com.example.uberorganizer.UserInterfaceTwo.SectionsPagerAdapter;

import android.app.Activity;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.AdapterView.OnItemClickListener;
import android.os.Build;

import com.example.uberorganizer.CalendarAdapter;

public class UserInterfaceThree extends FragmentActivity {// implements android.view.View.OnClickListener{

	public static GregorianCalendar month, itemmonth;
	public static CalendarAdapter adapter;
	SectionsPagerAdapter mSectionsPagerAdapter;
	public static Handler handler;
	public static ArrayList<String> items; // container to store calendar items
											// which
	static ArrayList<String> event;
	static LinearLayout rLayout;
	static ArrayList<String> date;
	static ArrayList<String> desc;
	static long millis;
	static int[] myDate = new int[3];
	ViewPager mViewPager;
 
	 private ArrayAdapter<String> listAdapter;  
	 

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_user_interface_three);
		items = new ArrayList<String>();  
		
		 handler = new Handler();  
		  handler.post(calendarUpdater);  

		  
		if (savedInstanceState == null) {
			getFragmentManager().beginTransaction()
					.add(R.id.container, new PlaceholderFragment()).commit();
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.user_interface_three, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {
		}
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			
				final View rootView = inflater.inflate(R.layout.calendar3,
						container, false);
				
				
				rLayout = (LinearLayout) rootView.findViewById(R.id.text);
				month = (GregorianCalendar) GregorianCalendar.getInstance();
				itemmonth = (GregorianCalendar) month.clone();

				

				adapter = new CalendarAdapter(rootView.getContext(), month);
				//handler = new Handler();
				//handler.post(calendarUpdater);

				TextView title = (TextView) rootView.findViewById(R.id.title);
				title.setText(android.text.format.DateFormat.format(
						"MMMM yyyy", month));
				Locale.setDefault(Locale.US);
				GridView gridview = (GridView) rootView
						.findViewById(R.id.gridview);
				gridview.setAdapter(adapter);
				gridview.setOnItemClickListener(new OnItemClickListener() {
					public void onItemClick(AdapterView parent, View v,
							int position, long id) {
						// usuwanie poprzedniego widoku jesli dodane
						if (((LinearLayout) rLayout).getChildCount() > 0) {
							((LinearLayout) rLayout).removeAllViews();
						}
						desc = new ArrayList<String>();
						date = new ArrayList<String>();
						((CalendarAdapter) parent.getAdapter()).setSelected(v);
						String selectedGridDate = CalendarAdapter.dayString
								.get(position);
						String[] separatedTime = selectedGridDate.split("-");
					    myDate[0]=Integer.parseInt(separatedTime[0]); // rok
					    myDate[1]=Integer.parseInt(separatedTime[1]); // miesiac
					    myDate[2]=Integer.parseInt(separatedTime[2]); // dzien
						String gridvalueString = separatedTime[2].replaceFirst(
								"^0*", "");// bierzemy ostatnia czesc daty (dni)
						int gridvalue = Integer.parseInt(gridvalueString);
						// nastepny albo poprzedni miesiac jesli wcisniemy dni
						// spoza biezacego miesiaca
						if ((gridvalue > 10) && (position < 8)) {
							setPreviousMonth();
							((UserInterfaceThree)getActivity()).
							refreshCalendar();
						} else if ((gridvalue < 7) && (position > 28)) {
							setNextMonth();
							((UserInterfaceThree)getActivity()).
							refreshCalendar();
						}
						((CalendarAdapter) parent.getAdapter()).setSelected(v);

						for (int i = 0; i < Utility.startDates.size(); i++) {
							if (Utility.startDates.get(i).equals(
									selectedGridDate)) {
								desc.add(Utility.nameOfEvent.get(i));
							}
						}

						if (desc.size() > 0) {
							for (int i = 0; i < desc.size(); i++) {
								TextView rowTextView = new TextView(rootView
										.getContext());

								// set some properties of rowTextView or
								// something
								rowTextView.setText("Event:" + desc.get(i));
								rowTextView.setTextColor(Color.BLACK);

								// add the textview to the linearlayout
								rLayout.addView(rowTextView);

							}

						}

						desc = null;
						
						
					}

					

				});
				RelativeLayout previous = (RelativeLayout) rootView
						.findViewById(R.id.previous);
				previous.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {

						setPreviousMonth();
						((UserInterfaceThree)getActivity()).
						refreshCalendar();

					}
				});

				// odswiezanie kalendarza na wcisnieciu dla przesuniecia
				// kalendarza o miesiac w przod
				RelativeLayout next = (RelativeLayout) rootView
						.findViewById(R.id.next);
				next.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {

						setNextMonth();
						((UserInterfaceThree)getActivity()).
						refreshCalendar();

					}
				});

				TextView textView = (TextView) rootView
						.findViewById(R.id.section_label);
				return rootView;
			}

			// textView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));

		}





protected static void setNextMonth() {
	if (month.get(GregorianCalendar.MONTH) == month
			.getActualMaximum(GregorianCalendar.MONTH)) {
		month.set((month.get(GregorianCalendar.YEAR) + 1),
				month.getActualMinimum(GregorianCalendar.MONTH), 1);
	} else {
		month.set(GregorianCalendar.MONTH,
				month.get(GregorianCalendar.MONTH) + 1);
	}

}

// przechodzenie do poprzedniego miesiaca
protected static void setPreviousMonth() {
	if (month.get(GregorianCalendar.MONTH) == month
			.getActualMinimum(GregorianCalendar.MONTH)) {
		month.set((month.get(GregorianCalendar.YEAR) - 1),
				month.getActualMaximum(GregorianCalendar.MONTH), 1);
	} else {
		month.set(GregorianCalendar.MONTH,
				month.get(GregorianCalendar.MONTH) - 1);
	}

}

// odswiezenie kalendarza
public void refreshCalendar() {
	TextView title = (TextView) findViewById(R.id.title);

	adapter.refreshDays();
	adapter.notifyDataSetChanged();
    handler.post(calendarUpdater); // generate some calendar items

	title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));
}

 public Runnable calendarUpdater = new Runnable() {  
	  
	  @Override  
	  public void run() {  
	   items.clear();  
	   // Print dates of the current week  
	   DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.US);  
	   String itemvalue;  
	   event = Utility.readCalendarEvent(UserInterfaceThree.this);  
	   listAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.simplerow,(List<String>)event);  
	  // mainListView.setAdapter( listAdapter ); 
	   for (int i = 0; i < Utility.startDates.size(); i++) {  
	    itemvalue = df.format(itemmonth.getTime());  
	    itemmonth.add(GregorianCalendar.DATE, 1);  
	    items.add(Utility.startDates.get(i).toString());  
	   }  
	   adapter.setItems(items);  
	   adapter.notifyDataSetChanged();  
	  }  
	  
	 };

	 
		public void showListDialog(View v)
		{
			FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
			ListDialog dial = new ListDialog(); // klasa odpowiedzialna za okienko dodawania wydarzen
			dial.setArguments(listAdapter);
			dial.show(ft, "showListDialog");
		}

public void addEvent(View v) {
		TimePicker tp = (TimePicker)findViewById(R.id.timePicker1);
		TextView textView = (TextView)findViewById(R.id.editText1);
		TextView textView2 = (TextView)findViewById(R.id.editText2);
		Calendar start = Calendar.getInstance();
		start.set(myDate[0], myDate[1] - 1,myDate[2], tp.getCurrentHour() , tp.getCurrentMinute(), 0);
	    Calendar end = Calendar.getInstance();
	    end.set(myDate[0], myDate[1] - 1,myDate[2], tp.getCurrentHour() +1 , tp.getCurrentMinute(), 0);
		Utility.putCalendarEvent(this,textView.getText().toString(),textView2.getText().toString(), start.getTimeInMillis(), end.getTimeInMillis());
		AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);

		dlgAlert.setMessage("Dodano");
		dlgAlert.setTitle("Wydarzenie");
		dlgAlert.setPositiveButton("Ok",
			    new DialogInterface.OnClickListener() {
			        public void onClick(DialogInterface dialog, int which) {
			          //dismiss the dialog  
			        }
			    });
		dlgAlert.setCancelable(true);
		dlgAlert.create().show();
	
		refreshCalendar();
	}
	


}
